const { WechatHome } = require('../../models/homeSchema.js')
const { fileUpload, checkFile } = require('../../utils/files.js')

const uploadFile = async (request, reply) => {
  const data = await request.file()
  if (!data.filename) {
    return reply.code(400).send({
      message: '未找到上传文件！',
      data: null,
      code: reply.statusCode,
      error: data.fieldname + '不能为空!',
    })
  }
  const setResult = await fileUpload(data, data.fieldname)
  const datas = {
    url: setResult.data.fileUrl,
    name: setResult.data.fileName,
    fileType: setResult.data.fileType,
    uid: setResult.data.fileTimeName,
  }
  return reply.code(200).send({
    data: datas,
    code: reply.statusCode,
  })
}

const wechatHomeSave = async (request, reply) => {
  const newData = new WechatHome(request.body)
  const saveData = await newData.save()
  if (saveData) {
    return reply.code(200).send({
      code: reply.statusCode,
      message: '保存成功！',
      data: null,
      error: null,
    })
  }
}
const wechatHomeList = async (request, reply) => {
  const dataList = await WechatHome.find({}, { __v: 0 })

  const obj = dataList.reduce((acc, item) => {
    acc = { ...acc, ...item }
    return acc
  }, {})

  if (dataList) {
    return reply.code(200).send({
      code: reply.statusCode,
      message: '',
      data: obj._doc,
      error: null,
    })
  }
}

module.exports = {
  uploadFile,
  wechatHomeSave,
  wechatHomeList,
}
